package com.jingyanzi.privilege.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.privilege.dao.SecurityOrganizationMapper;
import com.jingyanzi.privilege.dao.SecurityEmployeeMapper;
import com.jingyanzi.privilege.dao.SecurityJobsMapper;
import com.jingyanzi.privilege.domain.OrgDO;
import com.jingyanzi.privilege.domain.result.ResultDO;
import com.jingyanzi.privilege.domain.result.ResultSupport;
import com.jingyanzi.privilege.entity.SecurityEmployeeExample;
import com.jingyanzi.privilege.entity.SecurityJobs;
import com.jingyanzi.privilege.entity.SecurityJobsExample;
import com.jingyanzi.privilege.entity.SecurityOrganization;
import com.jingyanzi.privilege.entity.SecurityOrganizationExample;
import com.jingyanzi.privilege.entity.SecurityOrganizationExample.Criteria;
import com.jingyanzi.privilege.entity.SecurityEmployee;
import com.jingyanzi.privilege.query.OrgQueryDO;
import com.jingyanzi.privilege.service.IOrgService;
import com.jingyanzi.privilege.util.BeanUtilsExtends;

@Service("orgService")
public class OrgServiceImpl extends BaseServiceImpl implements IOrgService {

	@Autowired
	private SecurityOrganizationMapper orgMapper;

	@Autowired
	private SecurityEmployeeMapper employeeMapper;
	
	@Autowired
	private SecurityJobsMapper jobsMapper;
    
	/**
	 * 是否是叶子节点
	 * 
	 * @param id
	 * @return true 是叶子节点 false 不是叶子节点
	 */
	public boolean isNodeOrg(Integer id) {
		SecurityOrganization node = null;

		if (id == 0) {
			return false;
		}

		try {
			node = orgMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 不能在叶子节点下面添加节点
		if (node.getIsNode() == 1) {
			return true;
		}
		return false;
	}

	/**
	 * 是否是根节点
	 * 
	 * @param id
	 * @return true 是根节点 false 不是根节点
	 */
	public boolean isRoot(Integer id) {

		int count = 0;

		SecurityOrganizationExample example = new SecurityOrganizationExample();
		example.createCriteria().andOrgIdEqualTo(id);

		try {
			count = orgMapper.countByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 是否是根节点
		if (count > 0) {
			return true;
		}
		return false;
	}

	public ResultDO add(OrgDO orgDO) {

		SecurityOrganization org = new SecurityOrganization();

		ResultSupport result = BeanUtilsExtends.copy(org, orgDO);

		/*
		 * //不能在叶子节点下面添加节点 if(isNodeOrg(orgDO.getOrgId())) {
		 * result.setSuccess(false); return result; }
		 */

		if (!result.isSuccess()) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("对象转换失败");
			result.setSuccess(false);
			return result;
		}

		if (orgDO.getOrgId() == null)
			orgDO.setOrgId(0);

		org.setCreatetime(Calendar.getInstance().getTime());
		org.setStatus(1);
		org.setIsDelete(1);
		org.setIsNode(0);
		SecurityOrganization pOrg = null;

		try {
			pOrg = orgMapper.selectByPrimaryKey(org.getOrgId());
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取组织机构失败");
			result.setSuccess(false);
			return result;
		}

		String pcode = "";

		if (pOrg != null) {
			pcode = pOrg.getCode();
		}
		org.setCode(createOrgCode(orgDO.getOrgId(), pcode));
		if (pOrg != null) {
			org.setOrgId(pOrg.getId());
			org.setOrgName(pOrg.getNameCode());
		}

		int r = -1;
		try {
			r = orgMapper.insert(org);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("添加组织机构信息失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("添加组织机构信息失败");
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, org.getId());
		return result;
	}

	public String createOrgCode(Integer orgId, String pCode) {

		List<SecurityOrganization> list = null;
		
		
		SecurityOrganizationExample example = new SecurityOrganizationExample();
		example.createCriteria().andOrgIdEqualTo(orgId).andIsDeleteEqualTo(1);
		example.setOrderByClause("CODE DESC");

		try {
			list = orgMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		if (list.size() == 0) {
			if (pCode != null) {
				return pCode + "01";
			}
			return "01";
		}
		String code = list.get(0).getCode();
		String first = "";
		String last = "";
		if (code.length() > 2) {
			first = code.substring(0, code.length() - 2);
			last = code.substring(code.length() - 2);
		} else {
			last = code;
		}
		
		int value = Integer.parseInt(last);
		last = "" + (value + 1);
		if (last.length() == 1)
			last = "0" + last;
		System.out.println("new:" + (first+ last));
		return first + last;
	}

	public ResultDO remove(Integer id, Integer desId) {

		ResultSupport result = new ResultSupport();

		SecurityOrganization org = new SecurityOrganization();

		/*
		 * //不能在叶子节点下面添加节点 if(isNodeOrg(desId)) { result.setSuccess(false);
		 * return result; }
		 */

		try {
			org = orgMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取组织机构信息失败");
			result.setSuccess(false);
			return result;
		}

		if (org == null) {
			result.setErrorCode(ResultDO.ORG_DELETE_ERROR);
			result.setErrorMsg("不存在该组织机构");
			result.setSuccess(false);
			return result;
		}

		if (id == desId) {
			result.setErrorCode(ResultDO.ORG_DELETE_ERROR);
			result.setErrorMsg("移动的节点与被移动的相同");
			result.setSuccess(false);
			return result;
		}
		
		org.setIsDelete(-1);

		int r = -1;

		try {
			r = orgMapper.updateByPrimaryKeySelective(org);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("删除组织机构信息失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("删除组织机构信息失败");
			result.setSuccess(false);
			return result;
		}

		// 返回节点下面的子节点
		List<SecurityOrganization> list = getOrgSubNode(id);
		
		
		if(!checkMoveNode(id, desId)) {
			result.setErrorMsg("移动的节点不能为该节点的子节点");
			result.setSuccess(false);
			return result;
		}

		for (SecurityOrganization subOrg : list) {
			
			// 移动的节点不能与被移动节点相同
			if (subOrg.getId() != desId) {
				OrgDO orgDO = new OrgDO();
				orgDO.setId(subOrg.getId());
				orgDO.setOrgId(desId);
				modifi(orgDO);
			} else {
				result.setErrorCode(ResultDO.ORG_DELETE_ERROR);
				result.setErrorMsg("移动的节点与被移动的相同");
				result.setSuccess(false);
				return result;
			}
		}
	
		return result;
	}
	
	
	public ResultDO setNodeEmployeeAndJobData(Integer orgId, String code) {
		
		ResultSupport result = new ResultSupport();
		// 获得叶子节点中的数据
		SecurityEmployeeExample example = new SecurityEmployeeExample();
		example.createCriteria().andOrgIdEqualTo(orgId).andIsDeleteEqualTo(1);
	
		List<SecurityEmployee> list2 = null;
		try {
			list2 = employeeMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.ORG_DELETE_ERROR);
			result.setErrorMsg("获取叶子节点下的员工失败");
			result.setSuccess(false);
			return result;
		}
		for (SecurityEmployee employee : list2) {
			int ret = -1;
			// 为这些数据重新设置节点
			employee.setOrgId(orgId);
			employee.setCode(code);
			try {
				ret = employeeMapper.updateByPrimaryKey(employee);
			} catch (Exception e) {
				result.setErrorCode(ResultDO.ORG_DELETE_ERROR);
				result.setErrorMsg("为子节点下的员工重设组织机构失败");
				result.setSuccess(false);
				return result;
			}
			if (ret < 1) {
				result.setErrorCode(ResultDO.ORG_DELETE_ERROR);
				result.setErrorMsg("为子节点下的员工重设组织机构失败");
				result.setSuccess(false);
				return result;
			}
		}
		
		SecurityJobsExample example2 = new SecurityJobsExample();
		example2.createCriteria().andOrgIdEqualTo(orgId).andIsDeleteEqualTo(1);
		List<SecurityJobs> list3 = null;
		
		try {
			list3 = jobsMapper.selectByExample(example2);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.ORG_DELETE_ERROR);
			result.setErrorMsg("获取叶子节点下的员工失败");
			result.setSuccess(false);
			return result;
		}
		for (SecurityJobs jobs : list3) {
			int ret = -1;
			// 为这些数据重新设置节点
			jobs.setOrgId(orgId);
			jobs.setCode(code);
			try {
				ret = jobsMapper.updateByPrimaryKey(jobs);
			} catch (Exception e) {
				result.setErrorCode(ResultDO.ORG_DELETE_ERROR);
				result.setErrorMsg("为子节点下的岗位重设组织机构失败");
				result.setSuccess(false);
				return result;
			}
			if (ret < 1) {
				result.setErrorCode(ResultDO.ORG_DELETE_ERROR);
				result.setErrorMsg("为子节点下的岗位重设组织机构失败");
				result.setSuccess(false);
				return result;
			}
		}
		
		return result;
	}
	
	private boolean checkMoveNode(Integer srcId, Integer desId) {
		SecurityOrganization org = orgMapper.selectByPrimaryKey(srcId);
		SecurityOrganizationExample example = new SecurityOrganizationExample();
		
		example.createCriteria().andCodeLike(org.getCode() + "%");
		
		List<SecurityOrganization> list1 = null;
		
		try {
			list1 = orgMapper.selectByExample(example);
		} catch (Exception e) {
			return false;
		}
		
		for(SecurityOrganization o : list1) {
			if(o.getId().intValue() == desId) {
				return false;
			}
		}
		return true;
	}

	public ResultDO modifi(OrgDO orgDO) {

		SecurityOrganization group = new SecurityOrganization();
		
		ResultSupport result = BeanUtilsExtends.copy(group, orgDO);
		
		if (!result.isSuccess()) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("对象转换失败");
			result.setSuccess(false);
			return result;
		}
		System.out.println("check:" + (group.getId().intValue() == group.getOrgId().intValue()));
		if(group.getId().intValue() == group.getOrgId().intValue()) {
			result.setErrorMsg("移动的节点与被移动的相同");
			result.setSuccess(false);
			return result;
		}
		
		if(!checkMoveNode(group.getId(), group.getOrgId())) {
			result.setErrorMsg("移动的节点不能为该节点的子节点");
			result.setSuccess(false);
			return result;
		}
	
		//if(group.getOrgId() != 0) {
		SecurityOrganization pOrg = null;
		SecurityOrganization entity2 = null;
		try {
			pOrg = orgMapper.selectByPrimaryKey(group.getOrgId());
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取组织机构信息失败");
			System.out.println("获取组织机构信息失败");
			result.setSuccess(false);
			return result;
		}

		try {
			entity2 = orgMapper.selectByPrimaryKey(group.getId());
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取组织机构信息失败");
			result.setSuccess(false);
			return result;
		}
		System.out.println((group.getOrgId() != entity2.getOrgId()) + "============" + group.getCode() +" and " + entity2.getPcode());
	
		if(group.getOrgId() != entity2.getOrgId()) {
		
			String pcode = "";
	
			if (pOrg != null) {
				pcode = pOrg.getCode();
			}
			System.out.println("new Pcode:" + pcode);
			group.setCode(createOrgCode(group.getOrgId(), pcode));
			if (pOrg != null) {
				group.setOrgId(pOrg.getId());
				group.setOrgName(pOrg.getNameCode());
			}
		} 
		//} 
		
		int r = -1;
		try {
			r = orgMapper.updateByPrimaryKeySelective(group);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("修改组织机构信息失败");
			result.setSuccess(false);
			return result;
		}
		if (r < 1) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("修改组织机构信息失败");
			result.setSuccess(false);
			return result;
		}
		
		ResultDO res2 = setNodeEmployeeAndJobData(group.getId(), group.getCode());
		
		if(!res2.isSuccess()) {
			result.setErrorMsg("移动下面的员工与岗位出现问题");
			System.out.println("移动下面的员工与岗位出现问题");
			result.setSuccess(false);
			return result;
		}
		
		ResultDO res3 = moveSubOrg(group.getId());
		
		if(!res3.isSuccess()) {
			result.setErrorMsg("移动子机构出现问题");
			System.out.println("移动子机构出现问题");
			result.setSuccess(false);
			return result;
		}
		
		

		return result;
	}
	
	public ResultDO moveSubOrg(Integer id) {
		
		ResultSupport result = new ResultSupport();
		
		SecurityOrganizationExample example = new SecurityOrganizationExample();
		
		example.createCriteria().andOrgIdEqualTo(id).andIsDeleteEqualTo(1);
		
		List<SecurityOrganization> list1 = null;
		
		try {
			list1 = orgMapper.selectByExample(example);
		} catch (Exception e) {
			result.setSuccess(false);
			return result;
		}
		System.out.println("子节点数：" + list1.size());
		if(list1.size() == 0) {
			System.out.println("返回");
			return result;
		} else {
			SecurityOrganizationExample example2 = new SecurityOrganizationExample();
			example2.createCriteria().andOrgIdEqualTo(id);
			SecurityOrganization org = new SecurityOrganization();
			org.setOrgId(-1);
			orgMapper.updateByExampleSelective(org, example2);
		}
		ResultDO res = null;
		for(SecurityOrganization e : list1) {
			OrgDO orgDO = new OrgDO();
			orgDO.setId(e.getId());
			orgDO.setOrgId(id);
			
			System.out.println("修改CODE：" + e.getOrgId() + "修改父CODE:" + e.getId());
			
			res = modifi(orgDO);
			if(!res.isSuccess()) {
				System.out.println(res.getErrorMsg());
				return res;
			}
			
			res = moveSubOrg(e.getId());
			
		}
		return result;
	}

	/*public ResultDO moveOrg(Integer srcId, Integer desId) {

		ResultSupport result = new ResultSupport();

		SecurityOrganization group = new SecurityOrganization();

		// 不能在叶子节点下面添加节点
		if (isNodeOrg(desId)) {
			result.setSuccess(false);
			return result;
		}
		
		SecurityOrganization pOrg = null;

		try {
			pOrg = orgMapper.selectByPrimaryKey(desId);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取组织机构失败");
			result.setSuccess(false);
			return result;
		}

		int ret = -1;
		group.setId(srcId);
		group.setOrgId(desId);
		String pcode = "";

		if (pOrg != null) {
			pcode = pOrg.getCode();
		}
		group.setCode(createOrgCode(group.getOrgId(), pcode));
		if (pOrg != null) {
			group.setOrgId(pOrg.getId());
			group.setOrgName(pOrg.getNameCode());
		}
		try {
			ret = orgMapper.updateByPrimaryKeySelective(group);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("修改组织机构信息失败");
			result.setSuccess(false);
			return result;
		}
		if (ret < 1) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("修改组织机构信息失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}*/

	private List<SecurityOrganization> getOrgSubNode(Integer groupId) {

		List<SecurityOrganization> list = null;
		SecurityOrganizationExample example = new SecurityOrganizationExample();

		example.createCriteria().andOrgIdEqualTo(groupId).andIsDeleteEqualTo(1);

		try {
			list = orgMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}

	/**
	 * 返回所有节点
	 */
	public ResultDO getOrgAllNode(Integer orgId) {

		ResultSupport result = new ResultSupport();

		List<SecurityOrganization> list = null;
		SecurityOrganizationExample example = new SecurityOrganizationExample();

		example.createCriteria().andIdEqualTo(orgId).andOrgIdEqualTo(orgId).andIsDeleteEqualTo(1);

		try {
			list = orgMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取组织机构信息失败");
			result.setSuccess(false);
			return result;
		}

		List<OrgDO> orgDOList = null;
		orgDOList = getOrgDOList(list);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, orgDOList);

		return result;
	}

	public ResultDO get(Integer id) {

		ResultSupport result = new ResultSupport();

		if (id < 1) {
			result.setErrorCode(ResultDO.ORG_QUERY_ERROR);
			result.setErrorMsg("设置机构错误");
			result.setSuccess(false);
			return result;
		}

		SecurityOrganization org = null;

		try {
			org = orgMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取组织机构信息失败");
			result.setSuccess(false);
			return result;
		}

		if (org == null) {
			result.setErrorCode(ResultDO.ORG_QUERY_ERROR);
			result.setErrorMsg("该组织机构不存在");
			result.setSuccess(false);
			return result;
		}
		OrgDO orgDO = getOrgDO(org);
		orgDO.setChildren(list(orgDO.getId()));
		result.setModel(ResultSupport.FIRST_MODEL_KEY, orgDO);

		return result;
	}

	public ResultDO getOrgReverseList(Integer orgId) {

		ResultSupport result = new ResultSupport();

		result.setModel(ResultSupport.FIRST_MODEL_KEY, getOrgReverse(orgId));

		return result;

	}

	public List<OrgDO> getOrgReverse(Integer orgId) {

		List<OrgDO> orgList = new ArrayList<OrgDO>();

		SecurityOrganization org = null;

		try {
			org = orgMapper.selectByPrimaryKey(orgId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (org == null) {
			return orgList;
		} else {
			orgList.add(getOrgDO(org));
			orgList.addAll(getOrgReverse(org.getOrgId()));
		}
		return orgList;
	}

	public ResultDO getOrgList(Integer orgId) {

		ResultSupport result = new ResultSupport();

		result.setModel(ResultSupport.FIRST_MODEL_KEY, list(orgId));

		return result;

	}

	public List<OrgDO> list(Integer orgId) {

		List<SecurityOrganization> list = null;
		SecurityOrganizationExample example = new SecurityOrganizationExample();

		example.createCriteria().andOrgIdEqualTo(orgId).andIsDeleteEqualTo(1);
		example.setOrderByClause("sortNum asc");
		try {
			list = orgMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}

		
		List<OrgDO> orgDOList = new ArrayList<OrgDO>();

		if (list == null || list.size() == 0) {
			return orgDOList;
		}

		for (SecurityOrganization org : list) {
			OrgDO orgDO = getOrgDO(org);
			orgDO.setChildren(list(org.getId()));
			orgDOList.add(orgDO);
		}

		return orgDOList;
	}

	public ResultDO query(OrgQueryDO query) {

		ResultSupport result = new ResultSupport();

		List<SecurityOrganization> list = null;

		SecurityOrganizationExample example = new SecurityOrganizationExample();
		Criteria createCriteria = example.createCriteria();
		if (StringUtils.isNotBlank(query.getNamecode())) {
			createCriteria.andNameCodeLike("%" + query.getNamecode() + "%");
		}

		if (query.getIsNode() != null) {
			createCriteria.andIsNodeEqualTo(query.getIsNode());
		}

		createCriteria.andIsDeleteEqualTo(1);

		List<OrgDO> orgDOList = null;

		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = orgMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}
		
		example.setOrderByClause("sortNum asc");
		try {
			list = orgMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取组织机构信息失败");
			result.setSuccess(false);
			return result;
		}

		orgDOList = getOrgDOList(list);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, orgDOList);

		return result;
	}

}
